 package com.learn.ThreadPoolExecutor;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 池化：方便管理内存，最大化的效率  内存池、数据库链接池、对象池
 *
 * 池子满了: maxSize + queueSize < 任务数
 *
 * 拒绝策略 ：
 * AbortPolicy  池子满了就报错
 * CallerRunsPolicy  池子满了就返回原本的线程去执行 比如main
 * DiscardPolicy  池子满了直接放弃任务  不报错
 * DiscardOldestPolicy  池子满了尝试和最早的线程去竞争 没有就放弃任务  不报错
 *
 * 如何设计最大线程数量?
 * CPU密集型：服务器多少核心就定义多少，性能最大化 {获取当前服务器最大核心数 Runtime.getRuntime().availableProcessors()}
 * IO密集型：查询系统中最耗费内存的N个线程，定义最大线程为 2N 即可
 */
public class ThreadPollExtorDemo {

    public static final int COHESIVE = 2;
    public static final int KEEPALIVETIME = 1;
    public static final int QUEENIE = 3;

    public static void main(String[] args) {

        int i1 = Runtime.getRuntime().availableProcessors();

        System.out.println("Queue_Size = "+ QUEENIE);
        System.out.println("Local_Max_Core_Size = "+i1);
        System.out.println("Max_Work_Size = "+(i1+ QUEENIE));

        //自定义线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                COHESIVE,
                Runtime.getRuntime().availableProcessors(),
                KEEPALIVETIME,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(QUEENIE),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );

        try {
            for (int i = 1; i <= 9; i++) {
                final int temp = i;
                executor.execute(()->{
                    System.out.println(Thread.currentThread().getName());
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //所有的池使用完都需要手动关闭
            executor.shutdown();
        }
    }
}
